package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ProcessException;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.*;
import com.cskaoyan.order.dal.persistence.*;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    AddressMapper addressMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderDto createOrder(CreateOrderRequest request) {
        CreateOrderDto createOrderDto = new CreateOrderDto();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //从Context中获取订单Id
            String orderId = context.getOrderId();
            createOrderDto.setStatusCode(200);
            createOrderDto.setResult(orderId);
        } catch (Exception e) {
            if (e instanceof ValidateException) {
                createOrderDto.setStatusCode(500);
                createOrderDto.setResult(e.getMessage());
            } else if (e instanceof ProcessException) {
                createOrderDto.setStatusCode(500);
                createOrderDto.setResult(e.getMessage());
            } else if (e instanceof BizException) {
                createOrderDto.setStatusCode(500);
                createOrderDto.setResult(e.getMessage());
            } else if (e instanceof Exception) {
                // 处理不了，抛给调用方处理
                throw e;
            }

        }

        return createOrderDto;
    }

    @Override
    public void cancelOrder(String orderId) {
        // 设置 订单表 里 当前订单 的状态
        Example orderExample = new Example(Order.class);
        Example.Criteria criteria = orderExample.createCriteria();
        criteria.andEqualTo(orderId);
        Order order = new Order();
        order.setStatus(7);
        int i = orderMapper.updateByExample(order, orderExample);

        // 更新 库存表 中对应商品信息
        Example orderItemExample = new Example(OrderItem.class);
        Example.Criteria criteria1 = orderItemExample.createCriteria();
        criteria1.andEqualTo(orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        for (OrderItem orderItem : orderItemList) {
            Long itemId = orderItem.getItemId();
            Integer num = orderItem.getNum();

            Stock stock = new Stock();
            stock.setItemId(itemId);
            stock.setStockCount(((long) num));
            stock.setLockCount(-num);
            stockMapper.updateStock(stock);
        }

        // 设置对应的 订单商品表 里的数据状态
        Example orderItemExample1 = new Example(OrderItem.class);
        Example.Criteria criteria2 = orderItemExample1.createCriteria();
        criteria2.andEqualTo(orderId);
        OrderItem orderItem = new OrderItem();
        orderItem.setStatus(2);
        int i2 = orderItemMapper.updateByExampleSelective(orderItem, orderItemExample1);
    }

    @Override
    public void deleteOrder(String orderId) {
        int i = orderMapper.deleteByPrimaryKey(orderId);
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

    @Override
    public OrderListResponse getAllOrders(Integer page, Integer size, String sort) {
        // 返回值
        OrderListResponse response = new OrderListResponse();
        ArrayList<OrderDetailInfo> data = new ArrayList<>();
        response.setData(data);

        PageHelper.startPage(page, size);
        // 查订单
        List<Order> orderList = orderMapper.selectAll();

        PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);

        // 遍历查询每个 订单商品关联 和 订单物流
        for (Order order : orderList) {

            OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

            // 订单商品关联
            Example orderItemExample = new Example(OrderItem.class);
            Example.Criteria criteria = orderItemExample.createCriteria();
            criteria.andEqualTo("orderId", order.getOrderId());
            if (!StringUtils.isEmpty(sort)) {
                orderItemExample.orderBy(sort);
            }
            List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);

            List<OrderItemDto> orderItemDtoList = orderConverter.item2dto(orderItemList);
            orderDetailInfo.setOrderItemDto(orderItemDtoList);


            // 订单物流
            Example orderShippingExample = new Example(OrderShipping.class);
            Example.Criteria criteria1 = orderShippingExample.createCriteria();
            criteria1.andEqualTo("orderId", order.getOrderId());
            List<OrderShipping> orderShippingList = orderShippingMapper.selectByExample(orderShippingExample);

            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShippingList.get(0));
            orderDetailInfo.setOrderShippingDto(orderShippingDto);


            // 添加到 data
            data.add(orderDetailInfo);
        }


        response.setTotal(orderPageInfo.getTotal());

        return response;
    }

    @Override
    public OrderDetailResponse searchOrderById(Long orderId, Long uid) {
        // 返回值
        OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
        orderDetailResponse.setUserId(uid);


        // 从 订单表 中获得数据
        Order order = orderMapper.selectByPrimaryKey(orderId);
        orderDetailResponse.setOrderTotal(order.getPayment());
        orderDetailResponse.setOrderStatus(order.getStatus());

        // 从 订单物流表 中获得数据
        Example orderShippingExample = new Example(OrderShipping.class);
        Example.Criteria criteria = orderShippingExample.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        List<OrderShipping> orderShippingList = orderShippingMapper.selectByExample(orderShippingExample);
        OrderShipping orderShipping = orderShippingList.get(0);

        orderDetailResponse.setTel(orderShipping.getReceiverPhone());
        orderDetailResponse.setStreetName(orderShipping.getReceiverAddress());
        orderDetailResponse.setUserName(orderShipping.getReceiverName());


        // 从 订单商品表 中获得数据
        Example orderItemExample = new Example(OrderItem.class);
        Example.Criteria criteria1 = orderItemExample.createCriteria();
        criteria1.andEqualTo("orderId", orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        List<OrderItemDto> goodsList = orderConverter.item2dto(orderItemList);

        orderDetailResponse.setGoodsList(goodsList);


        return orderDetailResponse;
    }


}
